package com.lz.dsp.task.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.lz.dsp.task.dao", sqlSessionTemplateRef  = "adSqlSessionTemplate")
@PropertySource(value = {"classpath:/jdbc.properties"},ignoreResourceNotFound = true)
public class DataSourceConfigAd {

    @Bean(name = "adDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ad")
    @Primary
    public DataSource adDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "adSqlSessionFactory")
    @Primary
    public SqlSessionFactory adSqlSessionFactory(@Qualifier("adDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mybatis-config-ad.xml"));
        return bean.getObject();
    }

    @Bean(name = "adTransactionManager")
    @Primary
    public DataSourceTransactionManager adTransactionManager(@Qualifier("adDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "adSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate adSqlSessionTemplate(@Qualifier("adSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}